package guoanmaker.operator.business.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import guoanmaker.operator.business.dao.TrademarkSearchLogsDao;
import guoanmaker.operator.business.model.OperatorTrademarkAccount;
import guoanmaker.operator.business.model.OperatorTrademarkGettokenAccount;
import guoanmaker.operator.business.model.OperatorTrademarkSearchByUserLogs;
import guoanmaker.operator.business.model.OperatorTrademarkSearchLog;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.ResidueCount;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.model.Trademark;
import guoanmaker.operator.business.model.TrademarkFlow;
import guoanmaker.operator.business.model.TrademarkGood;
import guoanmaker.operator.business.modelnobind.TrademarkSearchLogs;
import guoanmaker.operator.business.repository.OperatorResidueCountRepository;
import guoanmaker.operator.business.repository.OperatorTrademarkAccountRepository;
import guoanmaker.operator.business.repository.OperatorTrademarkGettokenAccountRepository;
import guoanmaker.operator.business.repository.OperatorTrademarkSearchByUserLogsRepository;
import guoanmaker.operator.business.repository.OperatorTrademarkSearchLogRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.helper.common.abstractobj.TrademarkClassDictionary;
import guoanmaker.operator.helper.common.util.HttpGetUtil;

@Service
public class TrademarkAndPatentSearchService {
	
	
	@Autowired
	private PersonalUserRepository  personalUserRepository;
	@Autowired
	private OperatorResidueCountRepository operatorResidueCountRepository;
	@Autowired
	private TrademarkSearchLogsDao trademarkSearchLogsDao;
	@Autowired
	private OperatorTrademarkSearchByUserLogsRepository operatorTrademarkSearchByUserLogsRepository;
	@Autowired
	private OperatorTrademarkAccountRepository operatorTrademarkAccountRepository; 
	@Autowired
	private OperatorTrademarkGettokenAccountRepository gettokenAccountRepository;
	
	@Autowired
	private OperatorTrademarkSearchLogRepository trademarkSearchLogRepository;
	
	/**
	 * 
	* @Title: selectTrademarkInfo 
	* @Description: TODO(查询详情) 
	* @param @param id
	* @param @param regNo
	* @param @param intCls
	* @param @return
	* @param @throws UnsupportedEncodingException    入参
	* @return ReturnResult    返回类型
	* @author （ZhangXinYu） 
	* @throws
	* @date 2017年12月14日 上午10:58:20 
	* @version V1.0
	 */
	public  ReturnResult  selectTrademarkInfo(String id,String keyword ,String regNo , Integer intCls) throws UnsupportedEncodingException{
		ReturnResult returnResult=new ReturnResult();
		
		int status = 0;
		String data = null;
		String info= null;
		List<OperatorTrademarkSearchByUserLogs> trademarkSearchByUserLogss = operatorTrademarkSearchByUserLogsRepository.findByUseridAndRegNoAndIntCls(id, regNo, intCls);
		OperatorTrademarkAccount trademarkAccount = null;
		if(trademarkSearchByUserLogss != null && trademarkSearchByUserLogss.size() > 0 && trademarkSearchByUserLogss.get(0).getData() != null){
			// 从数据库缓存表中查询
			info = trademarkSearchByUserLogss.get(0).getData();
			status = 1;
		}else{
			List<OperatorTrademarkAccount> accounts = operatorTrademarkAccountRepository.findAllInfoAccount();
			if(accounts != null && accounts.size() > 0){
				//this.getToken(); // 调用接口查询数据  首先需要激活token	已在定时任务中激活
				trademarkAccount = accounts.get(0);
				String token = trademarkAccount.getAccount().trim();
				info = validateTrademarkInfo(token, regNo, intCls);
				data = new String(info);
			}else{
				returnResult.setKey("error");
				returnResult.setValue("查询次数已达上限");
				return returnResult;
			}
		}
		JSONObject openidobj = JSON.parseObject(info);//json解析
		String remainCount = openidobj.get("surplusAmount").toString();	// 取出接口剩余调用次数
		String retCode = openidobj.getString("code");
		//String retMsg = openidobj.get("message").toString();	//取出状态提示信息
		boolean success = openidobj.getBoolean("success");	//取出接口调用状态  true成功
		if(success && retCode.equals("000")){
			//000 为查询 成功代码
			//成功  取出字段
			JSONObject dataObj = (JSONObject) openidobj.get("data");	//取出返回数据集
//			System.out.println(dataObj);
			Trademark trademark = new Trademark();
			trademark.setTmImg(dataObj.getString("picUrl"));
			trademark.setTmName(new String(dataObj.get("sbmc").toString().getBytes(),"utf-8"));
			try{
				trademark.setAppDate(new Date(dataObj.getDate("sqrq").getTime()));
			}catch (Exception e) {
				trademark.setAppDate(null);
			}
			trademark.setIntCls(dataObj.getInteger("gjfl"));
			trademark.setClsType(TrademarkClassDictionary.trademarkClassDictionary.get(trademark.getIntCls()));
			String address = dataObj.get("sqrdzZw").toString();
			trademark.setAddress(address != null && !address.equals("") ? "国内" : "国外");	//中文地址为空则地址在国外
			trademark.setRegNo(dataObj.get("zch").toString());
//			trademark.setGjzcrq(openidobj.getDate("gjzcrq"));	//接口不存在国际注册日期   
			trademark.setApplicantCn(dataObj.getString("sqrmcZw"));	//设置申请人中文名 英文名
			trademark.setApplicantEn(dataObj.getString("sqrmcYw"));
			trademark.setAddressCn(dataObj.getString("sqrdzZw"));	//设置申请人中文地址 英文地址
			trademark.setAddressEn(dataObj.getString("sqrdzYw"));
			trademark.setAgent(dataObj.getString("dlrmc"));	//代理公司
			trademark.setPrivateDate(dataObj.getString("zyqqx"));	//有效日期
			//trademark.setIntCls(openidobj.getInteger("gjfl"));
			
			//输出商标流程信息字符串及商品字符串
			//System.out.println("商标流程："+dataObj.getString("sblc"));
			//System.out.println("使用商品："+dataObj.getString("sysp"));
			//商标流程：商标注册申请中(2016-04-01)--->商标注册申请受理通知书发文(2016-08-26)
			//使用商品：[1006--性用品;][1005--奶嘴，奶瓶;][1004--医疗用辅助器具，设备和用品;][1003--医疗用电、核子、电疗和X光设备;][1002--牙科设备及器具;][1001--外科、医疗和兽医用仪器、器械、设备，不包括电子、核子、电疗、医疗用Ｘ光设备、器械及仪器;][1009--缝合用材料;]
			//获取商品列表
			String goods = dataObj.getString("sysp");	//商标商品字符串
			if(goods != null && !goods.equals("")){
				String[] goodList = goods.replaceAll("\\[", "").replaceAll("\\]", "").split(";");	//去除[]分号分割每一个商品字符串
				List<TrademarkGood> trademarkGoods = new ArrayList<>();
				for (String good : goodList) {
					if (good != null && !good.equals("")) {
						TrademarkGood goodInfo = new TrademarkGood();
						String[] goodsInfos = good.split("--");	//0》》商品编号 1》》商品名称	// --分割每个商品字符串编号及名称
						if(goodsInfos.length == 2){
							goodInfo.setGoodsCode(goodsInfos[0]);
							goodInfo.setGoodsName(new String(goodsInfos[1].getBytes(),"utf-8"));
						}else{
							goodInfo.setGoodsCode(null);
							goodInfo.setGoodsName(new String(goodsInfos[0].getBytes(),"utf-8"));
						}
						//good.setBeDelete(jsonObject.getBoolean("beDeleted") ? 1 : 0);	//>>>0-未被删除  1-已被删除  //更换接口 路标网商标接口 不存在使用物品是否被删除字段
						trademarkGoods.add(goodInfo);
					}
				}
				trademark.setGoods(trademarkGoods);
			}
			//获取商标申请流程列表
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String flows = dataObj.getString("sblc");	//商标流程字符串
			if(flows != null && !flows.equals("")){
				String[] flowList = flows.split("--->");	//分割商标流程字符串
				List<TrademarkFlow> trademarkFlows = new ArrayList<>();
				for (String flow : flowList) {
					if(flow != null && !flow.equals("")){
						TrademarkFlow flowInfo = new TrademarkFlow();
						String[] flowInfos = flow.replace("\\)", "").split("\\(");	//数组0》》流程名称    1》》流程日期
						flowInfo.setFlowName(flowInfos[0]);
						if(flowInfos.length > 1){
							//length > 1 存在日期
							try {
								flowInfo.setFlowDate(simpleDateFormat.parse(flowInfos[1]));
							}catch (ParseException e) {
								e.printStackTrace();
								flowInfo.setFlowDate(null);
							}
						}else{
							//流程日期不存在   日期为null
							flowInfo.setFlowDate(null);
						}
						//商标申请流程code字段不存在  取消
						trademarkFlows.add(flowInfo);
					}
				}
				trademark.setFlows(trademarkFlows);
			}
			
			if(status == 0){
				//查询次数-1
				operatorResidueCountRepository.trademarkInfoSearchMinusOne();
				operatorResidueCountRepository.trademarkInfoSearchMinusOne(Integer.valueOf(remainCount));
				trademarkAccount.setInfoCount(Integer.valueOf(remainCount));
				operatorTrademarkAccountRepository.save(trademarkAccount);
				
				//记录用户查询历史
				PersonalUser personalUser = personalUserRepository.getOne(id);
				if(personalUser != null ){
					//String keywordStr = (String)session.getAttribute("trademarkKeyword");
					//OperatorTrademarkSearchLog operatorTrademarkSearchLog = trademarkSearchLogRepository.getOne((String)session.getAttribute("trademarkId"));
					List<OperatorTrademarkSearchLog> operatorTrademarkSearchLogs = trademarkSearchLogRepository.findAllSearchInfoLogsDesc(personalUser.getId());
					if(operatorTrademarkSearchLogs != null && operatorTrademarkSearchLogs.size() > 0){
						OperatorTrademarkSearchLog operatorTrademarkSearchLog = operatorTrademarkSearchLogs.get(0);
						if(operatorTrademarkSearchLog != null){
							if((operatorTrademarkSearchLog.getTmName() == null || operatorTrademarkSearchLog.getTmName().equals(""))&&
									(operatorTrademarkSearchLog.getTmCls() == null || operatorTrademarkSearchLog.getTmCls().equals(""))){
								//查询出记录最后一条记录为模糊查询	新插入详情
								operatorTrademarkSearchLog.setTmName(trademark.getTmName());
								operatorTrademarkSearchLog.setTmCls(trademark.getClsType());
							}else{
								//拼接详情
								operatorTrademarkSearchLog.setTmName(operatorTrademarkSearchLog.getTmName()+";"+trademark.getTmName());
								operatorTrademarkSearchLog.setTmCls(operatorTrademarkSearchLog.getTmCls()+";"+trademark.getClsType());
							}
							trademarkSearchLogRepository.save(operatorTrademarkSearchLog);
						}
					}
					
					//查询详情记录
					OperatorTrademarkSearchByUserLogs trademarkSearchByUserLogs = new OperatorTrademarkSearchByUserLogs();
					trademarkSearchByUserLogs.setUserid(id);
					trademarkSearchByUserLogs.setRegNo(regNo);
					trademarkSearchByUserLogs.setIntCls(intCls);
					trademarkSearchByUserLogs.setData(data);
					operatorTrademarkSearchByUserLogsRepository.save(trademarkSearchByUserLogs);
				}
			}

			trademark.setRemainCount(operatorResidueCountRepository.getTrademarkSearchInfo().getResidueCount());
			returnResult.setKey("trademark");
			returnResult.setValue(trademark);
			
		}else if(retCode.equals("006")){
			//006 为接口查询次数用尽代码
			returnResult.setKey("error");
			returnResult.setValue("本日查询次数已达上限");
		}else if(retCode.equals("400")){
			//400	您搜索的注册号暂时没有数据
			returnResult.setKey("error");
			returnResult.setValue("您搜索的注册号暂时没有数据");
		}else if(retCode.equals("401")){
			//401	注册号格式不符合规范
			returnResult.setKey("error");
			returnResult.setValue("注册号格式不符合规范");
		}else if(retCode.equals("401")){
			//402	商标分类为未知分类
			returnResult.setKey("error");
			returnResult.setValue("商标分类为未知分类");
		}else{
			if(retCode.equals("001")){
				//出现token 失效则激活token
				this.getToken();
			}
			//否则  输出接口调用出现的错误码及错误信息
			System.err.println("RetCode: "+retCode+"\nRetMsg: "+openidobj.getString("message"));
			returnResult.setKey("error_or");
			returnResult.setValue("RetCode: "+retCode+"\nRetMsg: "+openidobj.getString("message"));
		}

		return  returnResult;
	}
	/*@SuppressWarnings("unchecked")
	public  ReturnResult  selectTrademarkInfo(String id,String keyword ,String regNo , Integer intCls) throws UnsupportedEncodingException{
		ReturnResult returnResult=new ReturnResult();
		//apiKey        标库网分配给您的apiKey
		/**
		 * 公开测试用apiKey:TEST_APISTORE     apiPassword:0HTCv5hvPH  
		 */
		/*String  apiKey="A_NTuxVWGf";
		String  apiPassword="MR3mUVE32J";*
		/*String apiKey = "A_NdD8rGhd";
		String apiPassword = "J7qC8UzktG";*
		/*String apiKey = "A_AtFDS8PK";
		String apiPassword = "8jR7f5HJVJ";*
		
//		System.out.println(id);
//		System.out.println(session.getAttribute("trademarkId"));
		
		int status = 0;
		String data = null;
		String info= null;
		List<OperatorTrademarkSearchByUserLogs> trademarkSearchByUserLogss = operatorTrademarkSearchByUserLogsRepository.findByUseridAndRegNoAndIntCls(id, regNo, intCls);
		OperatorTrademarkAccount trademarkAccount = null;
		if(trademarkSearchByUserLogss != null && trademarkSearchByUserLogss.size() > 0 && trademarkSearchByUserLogss.get(0).getData() != null){
			info = trademarkSearchByUserLogss.get(0).getData();
			status = 1;
		}else{
			List<OperatorTrademarkAccount> accounts = operatorTrademarkAccountRepository.findAllInfoAccount();
			if(accounts != null && accounts.size() > 0){
				trademarkAccount = accounts.get(0);
				//次数-1
				//operatorTrademarkAccountRepository.divAccountInfoCount(trademarkAccount.getId());
				//operatorResidueCountRepository.trademarkInfoSearchMinusOne();
				String apiKey = trademarkAccount.getAccount();
				String apiPassword = trademarkAccount.getPassword();
				info = validateTrademarkInfo(apiKey, apiPassword, regNo, intCls);
				data = new String(info);
			}else{
				returnResult.setKey("error");
				//returnResult.setValue("本日查询次数已达上限");
				returnResult.setValue("查询次数已达上限");
				return returnResult;
			}
		}
		JSONObject openidobj = JSON.parseObject(info);//json解析
		String remainCount = openidobj.get("remainCount").toString();	// 取出remainCount
		String ret = openidobj.get("ret").toString();	//取出状态
		if(ret.equals("0")){
			//成功  取出字段
			Trademark trademark = new Trademark();
			trademark.setTmImg("http://pic.tmkoo.com/pic.php?zch="+openidobj.get("tmImg").toString()+"&amp;s=1");
			trademark.setTmName(new String(openidobj.get("tmName").toString().getBytes(),"utf-8"));
			trademark.setAppDate(new Date(openidobj.getDate("appDate").getTime()));
			trademark.setIntCls(openidobj.getInteger("intCls"));
			trademark.setClsType(TrademarkClassDictionary.trademarkClassDictionary.get(trademark.getIntCls()));
			String address = openidobj.get("addressCn").toString();
			trademark.setAddress(address != null && !address.equals("") ? "国内" : "国外");	//中文地址为空则地址在国外
			trademark.setRegNo(openidobj.get("regNo").toString());
			trademark.setGjzcrq(openidobj.getDate("gjzcrq"));
			trademark.setApplicantCn(openidobj.getString("applicantCn"));
			trademark.setApplicantEn(openidobj.getString("applicantEn"));
			trademark.setAgent(openidobj.getString("agent"));	//代理公司
			trademark.setPrivateDate(openidobj.getString("privateDate"));	//有效日期
			trademark.setIntCls(openidobj.getInteger("intCls"));
			//获取商品列表
			List<JSONObject> goodList = (List<JSONObject>) openidobj.get("goods");
			if(goodList != null && goodList.size() > 0){
				List<TrademarkGood> goods = new ArrayList<>();
				for (JSONObject jsonObject : goodList) {
					TrademarkGood good = new TrademarkGood();
					good.setGoodsCode(jsonObject.getString("goodsCode"));
					good.setGoodsName(new String(jsonObject.getString("goodsName").getBytes(),"utf-8"));
					good.setBeDelete(jsonObject.getBoolean("beDeleted") ? 1 : 0);	//>>>0-未被删除  1-已被删除
					goods.add(good);
				}
				trademark.setGoods(goods);
			}
			//获取商标申请流程列表
			List<JSONObject> flowList = (List<JSONObject>) openidobj.get("flow");
			if(flowList != null && flowList.size() > 0){
				List<TrademarkFlow> flows = new ArrayList<>();
				for (JSONObject jsonObject : flowList) {
					TrademarkFlow flow = new TrademarkFlow();
					flow.setCode(jsonObject.getString("code"));
					flow.setFlowName(jsonObject.getString("flowName"));
					flow.setFlowDate(jsonObject.getDate("flowDate"));
					flows.add(flow);
				}
				trademark.setFlows(flows);
			}
			
			if(status == 0){
				//查询次数-1
				operatorResidueCountRepository.trademarkInfoSearchMinusOne();
				operatorResidueCountRepository.trademarkInfoSearchMinusOne(Integer.valueOf(remainCount));
				trademarkAccount.setInfoCount(Integer.valueOf(remainCount));
				operatorTrademarkAccountRepository.save(trademarkAccount);
				
				//记录用户查询历史
				PersonalUser personalUser = personalUserRepository.getOne(id);
				if(personalUser != null ){
					//String keywordStr = (String)session.getAttribute("trademarkKeyword");
					//OperatorTrademarkSearchLog operatorTrademarkSearchLog = trademarkSearchLogRepository.getOne((String)session.getAttribute("trademarkId"));
					List<OperatorTrademarkSearchLog> operatorTrademarkSearchLogs = trademarkSearchLogRepository.findAllSearchInfoLogsDesc(personalUser.getId());
					if(operatorTrademarkSearchLogs != null && operatorTrademarkSearchLogs.size() > 0){
						OperatorTrademarkSearchLog operatorTrademarkSearchLog = operatorTrademarkSearchLogs.get(0);
						if(operatorTrademarkSearchLog != null){
							if((operatorTrademarkSearchLog.getTmName() == null || operatorTrademarkSearchLog.getTmName().equals(""))&&
									(operatorTrademarkSearchLog.getTmCls() == null || operatorTrademarkSearchLog.getTmCls().equals(""))){
								//查询出记录最后一条记录为模糊查询	新插入详情
								/*operatorTrademarkSearchLog = new OperatorTrademarkSearchLog();
								operatorTrademarkSearchLog.setKeyword(keyword);
								operatorTrademarkSearchLog.setDatetime(new Date());
								operatorTrademarkSearchLog.setTmName(trademark.getTmName());
								operatorTrademarkSearchLog.setTmCls(trademark.getClsType());
								personalUser.getTrademarks().add(operatorTrademarkSearchLog);
								operatorTrademarkSearchLog.setUser(personalUser);*
								operatorTrademarkSearchLog.setTmName(trademark.getTmName());
								operatorTrademarkSearchLog.setTmCls(trademark.getClsType());
							}else{
								//拼接详情
								operatorTrademarkSearchLog.setTmName(operatorTrademarkSearchLog.getTmName()+";"+trademark.getTmName());
								operatorTrademarkSearchLog.setTmCls(operatorTrademarkSearchLog.getTmCls()+";"+trademark.getClsType());
							}
							trademarkSearchLogRepository.save(operatorTrademarkSearchLog);
						}
					//List<OperatorTrademarkSearchLog> trademarkSearchLogs = trademarkSearchLogRepository.findAllSearchInfoLogsDesc(id);
					/*if(trademarkSearchLogs != null && trademarkSearchLogs.size() > 0){
						OperatorTrademarkSearchLog operatorTrademarkSearchLog = trademarkSearchLogs.get(0);*
					}
					
					/*OperatorTrademarkSearchLog operatorTrademarkSearchLog = new OperatorTrademarkSearchLog();
					operatorTrademarkSearchLog.setKeyword(keyword);
					operatorTrademarkSearchLog.setDatetime(new Date());
					operatorTrademarkSearchLog.setTmName(trademark.getTmName());
					operatorTrademarkSearchLog.setTmCls(trademark.getClsType());
					personalUser.getTrademarks().add(operatorTrademarkSearchLog);
					operatorTrademarkSearchLog.setUser(personalUser);*
//					personalUserRepository.save(personalUser);

					
					//查询详情记录
					OperatorTrademarkSearchByUserLogs trademarkSearchByUserLogs = new OperatorTrademarkSearchByUserLogs();
					trademarkSearchByUserLogs.setUserid(id);
					trademarkSearchByUserLogs.setRegNo(regNo);
					trademarkSearchByUserLogs.setIntCls(intCls);
					trademarkSearchByUserLogs.setData(data);
					operatorTrademarkSearchByUserLogsRepository.save(trademarkSearchByUserLogs);
				}
			}

			trademark.setRemainCount(operatorResidueCountRepository.getTrademarkSearchInfo().getResidueCount());
			returnResult.setKey("trademark");
			returnResult.setValue(trademark);
			
		}else if(ret.equals("1")&&remainCount.equals("0")){
			returnResult.setKey("error");
//			System.out.println(openidobj.get("msg").toString());
			returnResult.setValue("本日查询次数已达上限");
		}

		return  returnResult;
	}*/
	
	/**
	 * 
	* @Title: selectTrademarkList 
	* @Description: TODO(根据关键词查询商标列表) 
	* @param @param id
	* @param @param keyword
	* @param @param pageSize
	* @param @param pageNo
	* @param @param searchType
	* @param @param intCls
	* @param @return
	* @param @throws UnsupportedEncodingException    入参
	* @return ReturnResult    返回类型
	* @author （ZhangXinYu） 
	* @throws
	* @date 2017年12月14日 上午10:58:32 
	* @version V1.0
	 */
	@SuppressWarnings("unchecked")
	public ReturnResult selectTrademarkList(String id , String keyword , Integer pageSize , Integer pageNo , Integer intCls ) throws UnsupportedEncodingException{
		ReturnResult returnResult = new ReturnResult();
		List<OperatorTrademarkAccount> accounts = operatorTrademarkAccountRepository.findAllSearchAccount();
		if(accounts != null && accounts.size() > 0){
			//this.getToken(); // 调用接口查询数据  首先需要激活token	已在定时任务中获取token
			//this.validateToken();//激活token
			OperatorTrademarkAccount trademarkAccount = accounts.get(0); //获取token
			//次数-1
			//operatorTrademarkAccountRepository.divAccountSearchCount(trademarkAccount.getId());
			//operatorResidueCountRepository.trademarkSearchMinusOne();
			String token = trademarkAccount.getAccount().trim();
			String info = validateTrademarkList(token, keyword, pageSize, pageNo, intCls);
			//System.out.println("aasd");
			JSONObject openidobj = JSON.parseObject(info);//json解析
			String retCode = openidobj.getString("code");	//取出状态码
//			System.out.println(retCode);
			boolean success = openidobj.getBoolean("success");	//取出状态
			String remainCount = openidobj.getString("surplusAmount");	// 取出remainCount
			//String msg = openidobj.getString("msg");
			//System.out.println("ret:"+ret+"\tmsg:"+msg+"\tremainCount:"+remainCount);
			//operatorResidueCountRepository.trademarkSearchMinusOne();
			//System.out.println(remainCount);
			List<Trademark> trademarks = new ArrayList<>();
			if(success && retCode.equals("000")){
				/*无法判断分页查询的完整性  在前台调用清除方法*/
				/*if(!remainCount.equals("0")){
					operatorTrademarkSearchByUserLogsRepository.deleteByUserid(id);
				}*/
				/*pageNo = 0/1视为新的查询   清除缓存*/
				if(pageNo == 0 || pageNo == 1){
					operatorTrademarkSearchByUserLogsRepository.deleteByUserid(id);
				}
				//成功  取出字段
				JSONObject data = (JSONObject) openidobj.get("data");	//取出返回数据集
				List<JSONObject> list = (List<JSONObject>) data.get("brandList");	//取出结果集
				
				if(list != null && list.size() > 0){
					for (JSONObject object : list) {
						Trademark trademark = new Trademark();
						trademark.setRegNo(object.getString("zch"));
						trademark.setIntCls(object.getInteger("gjfl"));
						trademark.setClsType(TrademarkClassDictionary.trademarkClassDictionary.get(trademark.getIntCls()));
						trademark.setTmName(new String(object.get("sbwzLs").toString().getBytes(),"utf-8"));
						trademark.setTmImg(object.getString("picMiddle"));
						trademark.setAppDate(object.getDate("sqrq"));
						trademark.setCurrentStatus(object.getString("newProcess"));
						trademark.setApplicantCn(object.getString("sqrmcZw"));
						trademarks.add(trademark);
					}
				}
				
				Map<String,Object> map = new HashMap<>();
				map.put("trademarks", trademarks);
				//修改
				//pageNo =1 || =0 视为新的查询  无论新查询还是remainCount!=0 都进行查询次数从新统计
				/*if(!remainCount.equals("0") || (pageNo == 0 || pageNo == 1)){
					trademarkAccount.setSearchCount(Integer.valueOf(remainCount));
					operatorTrademarkAccountRepository.save(trademarkAccount);
					operatorResidueCountRepository.trademarkSearchMinusOne(Integer.valueOf(remainCount));
				}*/
				//每次都会消耗次数  不存在分页  则每次都会重置Token剩余次数
				trademarkAccount.setSearchCount(Integer.valueOf(remainCount));
				operatorTrademarkAccountRepository.save(trademarkAccount);
				operatorResidueCountRepository.trademarkSearchMinusOne(Integer.valueOf(remainCount));
				//获取查询详情剩余次数
				ResidueCount residueCount = operatorResidueCountRepository.getTrademarkSearchInfo();
				if(residueCount != null ){
					Integer Count = residueCount.getResidueCount();
					map.put("remainInfoCount", Count);
				}
				//获取模糊查询剩余次数
				residueCount = operatorResidueCountRepository.getTrademarkSearch();
				if(residueCount != null){
					Integer Count = residueCount.getResidueCount();
					map.put("remainSearchCount", Count);
				}
				//数据总条数
				map.put("allRecords", data.get("allRecords").toString());
				returnResult.setKey("success");
				returnResult.setValue(map);
				
				//记录用户查询历史
				PersonalUser personalUser = personalUserRepository.getOne(id);
				if(personalUser != null && pageNo <= 1){
					OperatorTrademarkSearchLog operatorTrademarkSearchLog = new OperatorTrademarkSearchLog();
					operatorTrademarkSearchLog.setKeyword(keyword);
					operatorTrademarkSearchLog.setDatetime(new Date());
					personalUser.getTrademarks().add(operatorTrademarkSearchLog);
					operatorTrademarkSearchLog.setUser(personalUser);
					//personalUserRepository.save(personalUser);
					operatorTrademarkSearchLog = trademarkSearchLogRepository.save(operatorTrademarkSearchLog);
					//session.setAttribute("trademarkId", operatorTrademarkSearchLog.getId());
				}
				
				//session.setAttribute("trademarkKeyword", keyword);
			}else if(retCode.equals("006")){
				//retCode == 006  //006为接口次数超限码
				returnResult.setKey("error");
				returnResult.setValue("查询次数已达上限");
				
				//设置查询次数-1  无法直接设置查询次数为0   因为当分页过程中出现错误是 返回ret=1  但是remainCount=0 即便仍有很多次数
				trademarkAccount = operatorTrademarkAccountRepository.findOne(trademarkAccount.getId());
				if(trademarkAccount != null && trademarkAccount.getSearchCount() > 0){
					trademarkAccount.setSearchCount(trademarkAccount.getSearchCount()-1);
					operatorTrademarkAccountRepository.save(trademarkAccount);
					operatorResidueCountRepository.trademarkSearchMinusOne();
				}
			}else if(retCode.equals("100")){
				//100	您搜索的词组暂时没有数据
				returnResult.setKey("error");
				returnResult.setValue("您搜索的词组暂时没有数据");
			}else if(retCode.equals("101")){
				//101	关键字包含特殊字符
				returnResult.setKey("error");
				returnResult.setValue("关键字不可以包含特殊字符");
			}else if(retCode.equals("102")){
				//102	商标分类为未知分类
				returnResult.setKey("error");
				returnResult.setValue("商标分类为未知分类");
			}else{
				if(retCode.equals("001")){
					//出现token 失效则激活token
					this.getToken();
				}
				//否则  输出接口调用出现的错误码及错误信息
				System.err.println("RetCode: "+retCode+"\nRetMsg: "+openidobj.getString("message")+"\tToken: "+token);
				returnResult.setKey("error_or");
				returnResult.setValue("RetCode: "+retCode+"\nRetMsg: "+openidobj.getString("message"));
			}
			
		}else{
			returnResult.setKey("error");
			returnResult.setValue("查询次数已达上限");
		}
		
		return returnResult;
	}
	/*@SuppressWarnings("unchecked")
	public ReturnResult selectTrademarkList(String id , String keyword , Integer pageSize , Integer pageNo , Integer intCls ) throws UnsupportedEncodingException{
		ReturnResult returnResult = new ReturnResult();
		/**
		 * 查询测试用 apiKey apiPassword
		 */
		/*String  apiKey="A_NTuxVWGf";
		String  apiPassword="MR3mUVE32J";
		String apiKey = "A_NdD8rGhd";
		String apiPassword = "J7qC8UzktG";
		String apiKey = "A_AtFDS8PK";
		String apiPassword = "8jR7f5HJVJ";*
		
		List<OperatorTrademarkAccount> accounts = operatorTrademarkAccountRepository.findAllSearchAccount();
		if(accounts != null && accounts.size() > 0){
			OperatorTrademarkAccount trademarkAccount = accounts.get(0);
			//次数-1
			//operatorTrademarkAccountRepository.divAccountSearchCount(trademarkAccount.getId());
			//operatorResidueCountRepository.trademarkSearchMinusOne();
			String apiKey = trademarkAccount.getAccount();
			String apiPassword = trademarkAccount.getPassword();
			
			String info = validateTrademarkList(apiKey, apiPassword, keyword, pageSize, pageNo, searchType, intCls);
			JSONObject openidobj = JSON.parseObject(info);//json解析
			String remainCount = openidobj.get("remainCount").toString();	// 取出remainCount
			String ret = openidobj.get("ret").toString();	//取出状态
			//String msg = openidobj.getString("msg");
			//System.out.println("ret:"+ret+"\tmsg:"+msg+"\tremainCount:"+remainCount);
			//operatorResidueCountRepository.trademarkSearchMinusOne();
			System.out.println(remainCount);
			List<Trademark> trademarks = new ArrayList<>();
			List<JSONObject> list = (List<JSONObject>) openidobj.get("results");	//取出结果集
			if(ret.equals("0") || (list != null && list.size() > 0)){
				/*无法判断分页查询的完整性  在前台调用清除方法*
				/*if(!remainCount.equals("0")){
					operatorTrademarkSearchByUserLogsRepository.deleteByUserid(id);
				}*/
				/*pageNo = 0/1视为新的查询   清除缓存*
				if(pageNo == 0 || pageNo == 1){
					operatorTrademarkSearchByUserLogsRepository.deleteByUserid(id);
				}
				//成功  取出字段
				
				if(list != null && list.size() > 0){
					for (JSONObject object : list) {
						Trademark trademark = new Trademark();
						trademark.setRegNo(object.getString("regNo"));
						trademark.setIntCls(object.getInteger("intCls"));
						trademark.setClsType(TrademarkClassDictionary.trademarkClassDictionary.get(trademark.getIntCls()));
						trademark.setTmName(new String(object.get("tmName").toString().getBytes(),"utf-8"));
						trademark.setTmImg("http://pic.tmkoo.com/pic.php?zch="+object.getString("tmImg")+"&amp;s=1");
						trademark.setAppDate(object.getDate("appDate"));
						trademark.setCurrentStatus(object.getString("currentStatus"));
						trademark.setApplicantCn(object.getString("applicantCn"));
						trademarks.add(trademark);
					}
				}
				
				Map<String,Object> map = new HashMap<>();
				map.put("trademarks", trademarks);
				//修改
				//pageNo =1 || =0 视为新的查询  无论新查询还是remainCount!=0 都进行查询次数从新统计
				if(!remainCount.equals("0") || (pageNo == 0 || pageNo == 1)){
					trademarkAccount.setSearchCount(Integer.valueOf(remainCount));
					operatorTrademarkAccountRepository.save(trademarkAccount);
					operatorResidueCountRepository.trademarkSearchMinusOne(Integer.valueOf(remainCount));
				}
				//获取查询剩余次数
				ResidueCount residueCount = operatorResidueCountRepository.getTrademarkSearchInfo();
				if(residueCount != null ){
					Integer Count = residueCount.getResidueCount();
					map.put("remainInfoCount", Count);
				}
				//获取模糊查询剩余次数
				residueCount = operatorResidueCountRepository.getTrademarkSearch();
				if(residueCount != null){
					Integer Count = residueCount.getResidueCount();
					map.put("remainSearchCount", Count);
				}
				//数据总条数
				map.put("allRecords", openidobj.get("allRecords").toString());
				returnResult.setKey("success");
				returnResult.setValue(map);
				
				//记录用户查询历史
				PersonalUser personalUser = personalUserRepository.getOne(id);
				if(personalUser != null && pageNo <= 1){
					OperatorTrademarkSearchLog operatorTrademarkSearchLog = new OperatorTrademarkSearchLog();
					operatorTrademarkSearchLog.setKeyword(keyword);
					operatorTrademarkSearchLog.setDatetime(new Date());
					personalUser.getTrademarks().add(operatorTrademarkSearchLog);
					operatorTrademarkSearchLog.setUser(personalUser);
					//personalUserRepository.save(personalUser);
					operatorTrademarkSearchLog = trademarkSearchLogRepository.save(operatorTrademarkSearchLog);
					//session.setAttribute("trademarkId", operatorTrademarkSearchLog.getId());
				}
				
				//session.setAttribute("trademarkKeyword", keyword);
			}else if(ret.equals("1")){
				returnResult.setKey("error");
				returnResult.setValue("查询次数已达上限");
				
				//设置查询次数-1  无法直接设置查询次数为0   因为当分页过程中出现错误是 返回ret=1  但是remainCount=0 即便仍有很多次数
				trademarkAccount = operatorTrademarkAccountRepository.findOne(trademarkAccount.getId());
				if(trademarkAccount != null && trademarkAccount.getSearchCount() > 0){
					trademarkAccount.setSearchCount(trademarkAccount.getSearchCount()-1);
					operatorTrademarkAccountRepository.save(trademarkAccount);
					operatorResidueCountRepository.trademarkSearchMinusOne();
				}
				//设置查询次数为0
				/*
				trademarkAccount.setSearchCount(Integer.valueOf(remainCount));
				operatorTrademarkAccountRepository.save(trademarkAccount);
				operatorResidueCountRepository.trademarkSearchMinusOne(Integer.valueOf(remainCount));
				**
				/*trademarkAccount.setSearchCount(0);
				operatorTrademarkAccountRepository.save(trademarkAccount);
				operatorResidueCountRepository.trademarkSearchMinusOne(0);
			}
			
		}else{
			returnResult.setKey("error");
			//returnResult.setValue("本日查询次数已达上限");
			returnResult.setValue("查询次数已达上限");
		}
		
		return returnResult;
	}
	*/
	
	/**
	 * 
	* @Title: trademarkSearchLog 
	* @Description: TODO(商标接口查询记录) 
	* @param @return    入参
	* @return ReturnResult    返回类型
	* @author （ZhangXinYu） 
	* @throws
	* @date 2017年12月15日 上午8:59:04 
	* @version V1.0
	 */
	public ReturnResult trademarkSearchLog(String name,String username ,String keyword , String startDate , String endDate , Integer currentPage , Integer pageSize){
		ReturnResult returnResult = new ReturnResult();
		List<TrademarkSearchLogs> trademarkSearchLogs = trademarkSearchLogsDao.findTrademarkSearchLogs(name,username,keyword,startDate,endDate , currentPage , pageSize);
		if(trademarkSearchLogs != null){
			//获取模糊及详情接口剩余查询次数,接口查询历史记录
			ResidueCount residueSearchCount = operatorResidueCountRepository.getTrademarkSearch();
			ResidueCount residueSearchInfoCount = operatorResidueCountRepository.getTrademarkSearchInfo();
			Map<String, Object> map = new HashMap<>();
			map.put("searchRemainCount", residueSearchCount.getResidueCount());
			map.put("lastSearchDate", residueSearchCount.getLastQueryDate());
			map.put("searchInfoRemainCount", residueSearchInfoCount.getResidueCount());
			map.put("lastSearchInfoDate", residueSearchInfoCount.getLastQueryDate());
			map.put("trademarkSearchLogs", trademarkSearchLogs);
			map.put("trademarkTotalCount", trademarkSearchLogsDao.findTrademarkSearchLogsCount(name, username, keyword, startDate, endDate));
			returnResult.setKey("trademarkSearchLog");
			returnResult.setValue(map);
		}else{
			returnResult.setKey("error");
			returnResult.setValue("查询错误");
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Title: trademarkLogCount 
	* @Description: TODO(接口查询总记数) 
	* @param @return    入参
	* @return ReturnResult    返回类型
	* @author （ZhangXinYu） 
	* @throws
	* @date 2017年12月17日 下午5:27:36 
	* @version V1.0
	 */
	public ReturnResult trademarkLogCount(){
		ReturnResult returnResult = new ReturnResult();
		returnResult.setKey("count");
		returnResult.setValue(trademarkSearchLogRepository.count());
		return returnResult;
	}
	
	/**
	 * 
	* @Title: trademarkRemainCount 
	* @Description: TODO(商标查询接口剩余次数) 
	* @param @return    入参
	* @return ReturnResult    返回类型
	* @author （ZhangXinYu） 
	* @throws
	* @date 2017年12月22日 下午1:22:41 
	* @version V1.0
	 */
	public ReturnResult trademarkRemainCount(){
		ReturnResult returnResult = new ReturnResult();
		OperatorTrademarkAccount trademarkAccount = new OperatorTrademarkAccount();
		trademarkAccount.setSearchCount(operatorResidueCountRepository.getTrademarkSearch().getResidueCount());
		trademarkAccount.setInfoCount(operatorResidueCountRepository.getTrademarkSearchInfo().getResidueCount());
		returnResult.setKey("tradematkAccount");
		returnResult.setValue(trademarkAccount);
		return returnResult;
	}
	
	/**
	 * 
	 * 
	 * 获取指定商标的详细信息
	 * @param  apiKey        标库网分配给您的apiKey
	 * @param  apiPassword   标库网分配给您的apiPassword
	 * @param  regNo         注册号/申请号
	 * @param  intCls        国际分类
	 * @return 
	 * @throws UnsupportedEncodingException
	 */
	/*public static String validateTrademarkInfo(String apiKey, String apiPassword, String regNo,
			Integer intCls) throws UnsupportedEncodingException {
		String a = "http://api.tmkoo.com/info.php?";
		String b ="apiKey=" + URLEncoder.encode(apiKey,"utf-8") + "&apiPassword=" + URLEncoder.encode(apiPassword,"utf-8") + 
				"&regNo=" + URLEncoder.encode(regNo,"utf-8")+"&intCls="+intCls;
		String	oinfoma = HttpGetUtil.httpBigGet(a+b);
		System.out.println(oinfoma);
		/*com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println(openidobj);*
	/*	String status = (String) openidobj.get("status");// 取出status SUCCESS
		System.out.println(status);*
		return oinfoma;
	}*/
	public static String validateTrademarkInfo(String token, String regNo,Integer intCls) throws UnsupportedEncodingException {
		String a = "http://so.chatm.com/api/searchDetail/"
						+URLEncoder.encode(token, "utf-8")+"/"
						+regNo+"/"
						+intCls;
		String	oinfoma = HttpGetUtil.httpBigGet(a);
		return oinfoma;
	}
	
	/**
	 * 
	* @Title: validateTrademarkList 
	* @Description: TODO(根据关键词查询商标列表) 
	* @param @param apiKey			标库网分配给您的apiKey
	* @param @param apiPassword		标库网分配给您的apiPassword
	* @param @param keyword			查询关键词
	* @param @param pageSize		分页查询每页查询数据条数	0不分页
	* @param @param pageNo			分页查询页数		pageSize=0  改参数不起作用
	* @param @param searchType		查询方式：		1: 商标名， 2：注册号， 3：申请人 4：商标名/注册号/申请人只要匹配到就算
	* @param @param intCls			国际分类		0：全部国际分类	非0：限定在指定类别，类别间用分号分割。如：4;12;34  表示在第4、12、34类内查询

	* @param @return
	* @param @throws UnsupportedEncodingException    入参
	* @return List    返回类型
	* @author （ZhangXinYu） 
	* @throws
	* @date 2017年11月24日 上午11:00:54 
	* @version V1.0
	 */
	/*public static String validateTrademarkList(String apiKey , String apiPassword ,String keyword , Integer pageSize , Integer pageNo , Integer searchType , Integer intCls ) throws UnsupportedEncodingException{
		String a = "http://api.tmkoo.com/search.php?";
		String b = "apiKey=" + URLEncoder.encode(apiKey, "utf-8") 
				 + "&apiPassword=" + URLEncoder.encode(apiPassword, "utf-8")
				 + "&keyword=" + URLEncoder.encode(keyword, "utf-8")
				 + "&pageSize=" + pageSize
				 + "&pageNo=" + pageNo
				 + "&searchType=" + searchType
				 + "&intCls=" + intCls;
		String oinfoma = HttpGetUtil.httpBigGet(a+b);
		//System.out.println(oinfoma);
		com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println("tmName: "+openidobj.get("tmName"));
		return oinfoma;
	}*/
	public static String validateTrademarkList(String token ,String keyword , Integer pageSize , Integer pageNo , Integer intCls ) throws UnsupportedEncodingException{
		//http://so.chatm.com/api/searchKeyword/{token}/{keyword}/{gjfl}/{pageNo}/{pageSize}
		String a = "http://so.chatm.com/api/searchKeyword/"
								+URLEncoder.encode(token, "utf-8")+"/"
								+URLEncoder.encode(keyword, "utf-8")+"/"
								+intCls+"/"
								+pageNo+"/"
								+pageSize;
		String oinfoma = HttpGetUtil.httpBigGet(a);
		return oinfoma;
	}
	
	/**
	 * 
	* @Title: getToken 
	* @Description: TODO(根据用户名 密码 获取token) 
	* @param @param username
	* @param @param password
	* @param @return    入参
	* @return String    返回类型
	* @author （ZhangXinYu） 
	* @throws
	* @date 2018年1月3日 下午4:02:22 
	* @version V1.0
	 */
	public ReturnResult getToken()throws UnsupportedEncodingException{
		ReturnResult returnResult = new ReturnResult();
		//从数据库表中获取账户 密码 以用来激活token
		OperatorTrademarkGettokenAccount getTokenAccount = gettokenAccountRepository.findAll().get(0);
		String username = getTokenAccount.getUsername();
		String password = getTokenAccount.getPassword();
		OperatorTrademarkAccount trademarkAccount = operatorTrademarkAccountRepository.findAll().get(0);	//获取表中第一条token
		String a = "http://so.chatm.com/api/getToken/"+URLEncoder.encode(username, "utf-8")+"/"+URLEncoder.encode(password, "utf-8");
		String oinfoma = HttpGetUtil.httpBigGet(a);
		JSONObject openidobj = JSON.parseObject(oinfoma);
		String code = openidobj.getString("code");
		if(code.equals("000")){
			//请求成功	判断返回token与数据库token是否相同  不同则更换数据库token
			JSONObject data = openidobj.getJSONObject("data");
			String token = data.getString("token");
			if(!token.equals(trademarkAccount.getAccount().trim())){
				// 如果返回token与数据库存储token不一致   更新数据库token
				trademarkAccount.setAccount(token.trim());
				operatorTrademarkAccountRepository.save(trademarkAccount);
			}//token与数据库token一致 则只激活  不做操作
			//返回激活token
			returnResult.setKey("Success");
			returnResult.setValue(token);
		}else{
			//请求失败   打印 返回请求失败信息
			//否则  输出接口调用出现的错误码及错误信息
			System.err.println("RetCode: "+code+"\nRetMsg: "+openidobj.getString("message")+"\tToken: "+trademarkAccount.getAccount());
			returnResult.setKey("error_or");
			returnResult.setValue("RetCode: "+code+"\nRetMsg: "+openidobj.getString("message"));
		}
		/*result.setKey("GotSucceed");
		result.setValue(oinfoma);*/
		return returnResult;
	}
	
	public void validateToken()throws UnsupportedEncodingException{
		//从数据库表中获取账户 密码 以用来激活token
		OperatorTrademarkGettokenAccount getTokenAccount = gettokenAccountRepository.findAll().get(0);
		String username = getTokenAccount.getUsername();
		String password = getTokenAccount.getPassword();
		String a = "http://so.chatm.com/api/getToken/"+URLEncoder.encode(username, "utf-8")+"/"+URLEncoder.encode(password, "utf-8");
		HttpGetUtil.httpBigGet(a);
	}
}
